# -*- coding: utf-8 -*-
# @File : .py
# @Author : ZhouHang
# @Date : 20-4-10
# @Desc :
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from users.models import User
from .utils import OAuthQQ


class OAuthQQUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    access_token = serializers.CharField(label="操作凭证", write_only=True)
    token = serializers.CharField(label="jwt", read_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'token', 'id', 'username')

        extra_kwargs = {

            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, attrs):
        # 检测access_token
        access_token = attrs.get("access_token")
        openid = OAuthQQ.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError("无效的access_token")
        attrs['openid'] = openid
        # 检测手机验证码
        mobile = attrs.get("mobile")
        sms_code = attrs.get("sms_code")
        password = attrs.get("password")
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s'%mobile)
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError("手机验证码错误")
        # 判断是否存在用户　如果存在　检测用户密码　成功　颁发jwt 不存在则先创建用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果用户不存在　则先创建用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            if user.check_password(password):
                attrs['user'] = user
                return attrs
            else:
                raise serializers.ValidationError("密码错误")

    def create(self, validated_data):
        print("进来看看")
        openid = validated_data['openid']
        user = validated_data.get('user')
        mobile = validated_data['mobile']
        password = validated_data['password']

        if not user:
            # 如果用户不存在，创建用户，绑定openid（创建了OAuthQQUser数据）
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)

        OAuthQQUser.objects.create(user=user, openid=openid)

        # 签发jwt token
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        # payload = jwt_payload_handler(user)
        # token = jwt_encode_handler(payload)
        token = OAuthQQ.generate_jwt_code(user)
        user.token = token

        return user

